//
//  CalcViewController.m
//  Calc
//
//  Created by 黄 晨 on 11-10-9.
//  Copyright 2011年 北京火星时代科技有限公司. All rights reserved.
//

#import "CalcViewController.h"
#import "ScCalcViewController.h"

@implementation CalcViewController

@synthesize display,scCalcView;

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    ScCalcViewController *viewController = [[ScCalcViewController alloc] initWithNibName:@"ScCalcViewController" bundle:nil];
    
    self.scCalcView = viewController;
    [viewController release];
    
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.scCalcView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark Main Functions
// 点击数字
- (IBAction) numberClicked:(id)sender
{
    UIButton *btn = (UIButton *) sender;
    int tag = [btn tag];
    
    if([[display text] length] <= 10)
    {
        // 如果点击的是 .
        if (kDotTag == tag) 
        {
            dotOffset = 0 == dotOffset ? 1 : dotOffset;
        }
        // 如果点击的是数字
        else
        {
            if (0 == dotOffset) 
            {
                int number = [[display text] intValue];
                number = number*10 + tag;
                [display setText:[[NSString alloc] initWithFormat:@"%d", number]];
            }
            else
            {
                double number = [[display text] doubleValue];
                number = number + tag * pow(0.1, dotOffset++);
                [display setText:[[NSString alloc] initWithFormat:@"%g", number]];
            }
            
        }
    }
}

// 点击操作
- (IBAction) operaterClicked:(id)sender
{
    UIButton *btn = (UIButton *) sender;
    Operator op = [btn tag];
    switch (op) {
        // 等于
        case equal:
            if (0 != leftOperand && 0 != operater) {
                leftOperand = [self calculate:operater rightOperand:[[display text] doubleValue]];
                [display setText:[[NSString alloc] initWithFormat:@"%g", leftOperand]];
                operater = 0;
            }
            break;
            
        // 重置   
        case reset:
            [self clear:sender];
            break;
            
        // 设置左操作数
        default:
            leftOperand = [[display text] doubleValue];
            [display setText:@"0"];
            operater = op;
            dotOffset = 0;
            break;
    }
}

// 计算
- (double) calculate:(Operator)op rightOperand:(double) rightOperand
{
    double result = 0;
    
    switch (op) {
        // 加    
        case plus:
            result = leftOperand + rightOperand;
            break;
        // 减   
        case minus:
            result = leftOperand - rightOperand;
            break;
        // 乘   
        case times:
            result = leftOperand * rightOperand;
            break;
        // 除   
        case divide:
            if (0 == rightOperand) 
            {
                [self divideZero];
            }
            else
            {
                result = leftOperand / rightOperand;
            }
            break;
            
        default:
            break;
    }
    return result;
}

// 清除结果及操作
- (void) clear:(id)sender
{
    [display setText:@"0"];
    leftOperand = 0;
    operater = 0;
    dotOffset = 0;
}

// 显示被除数为零错误
- (void) divideZero 
{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error！" 
													message:@"Divisor must not be zero！"
												   delegate:self 
										  cancelButtonTitle:@"OK" 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];
}


// 点击内存操作
- (IBAction) memoryOperaterClicked:(id)sender
{
    UIButton *btn = (UIButton *) sender;
    Operator op = [btn tag];
    switch (op) {
            // M+
        case mplus:
            [self updateMemoryValue:[[display text] doubleValue] operate:@"plus"];
            break;
            
            // M-
        case minus:
            [self updateMemoryValue:[[display text] doubleValue] operate:@"minus"];
            break;
            
            // MR
        case mread:
            [self readMemoryValue];
            break;
            
        default:
            break;
    }
}

// 读取存储的数据
- (void) readMemoryValue
{
    if (0 == leftOperand) {
        leftOperand = mValue;
    }
    [display setText:[[NSString alloc] initWithFormat:@"%g", mValue]];
}

// 修改存储的值
- (void) updateMemoryValue:(double)value operate:(NSString *)op
{
    if ([op isEqualToString:@"plus"]) {
        mValue += value;
    }
    else if([op isEqualToString:@"minus"]){
        mValue -= value;
    }
}


- (void)orientationChanged:(NSNotification *)notification
{
    // We must add a delay here, otherwise we'll swap in the new view
	// too quickly and we'll get an animation glitch
    [self performSelector:@selector(updateLandscapeView) withObject:nil afterDelay:0];
}

- (void)updateLandscapeView
{
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    if (UIDeviceOrientationIsLandscape(deviceOrientation) && !isScCalc)
	{
        [self presentModalViewController:self.scCalcView animated:YES];
        [[self.scCalcView display] setText:[self.display text]];
        isScCalc = YES;
    }
	else if (isScCalc)
	{
        [self.display setText:[[self.scCalcView display] text]];
        [self dismissModalViewControllerAnimated:YES];
        isScCalc = NO;
    }    
}

- (void)dealloc {
    [super dealloc];
    
    [[NSNotificationCenter defaultCenter] removeObject:self];
    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
    [scCalcView release];
}

@end
